package com.asiainfo.dacp.datastash.orm.dao.core;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.asiainfo.dacp.datastash.orm.po.core.DataStashUnitPo;

/**
 * Created by winter on 2017/10/31.
 */
@Repository
public interface DataStashUnitDao extends JpaRepository<DataStashUnitPo,String>,JpaSpecificationExecutor<DataStashUnitPo> {

    @Query("select p from DataStashUnitPo p where p.unitCode=:unitCode ")
    DataStashUnitPo findListByUnitCode(@Param("unitCode") String unitCode );
    
    @Transactional
	@Modifying
	@Query("update DataStashUnitPo p set p.state=:state where p.id=:id")
    void updateState(@Param("id") String id,@Param("state") String state);

    @Transactional
    @Modifying
    @Query("update DataStashUnitPo p set p.batchNo=:batchNo where p.unitCode=:unitCode")
    void updateBatchNo(@Param("unitCode") String unitCode,@Param("batchNo") String batchNo);

    List<DataStashUnitPo> findByState(String state);
    
    @Query(value = "select * from dacp_datastash_unit o "
    		+ "where state = '1' and not exists "
    		+ "(select 1 from dacp_datastash_unit_state i "
    		+ "where i.unit_code=o.unit_code and i.batch_no= o.batch_no and i.is_over=1)", nativeQuery = true)
    List<DataStashUnitPo> findAllOnlineAndNotRunning();
}